package org.cleverframe.core.wfsnaker.engine;

import java.sql.Blob;
import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.Session;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.jdbc.Work;
import org.snaker.engine.DBAccess;
import org.snaker.engine.SnakerException;
import org.snaker.engine.access.ScriptRunner;
import org.snaker.engine.access.hibernate.HibernateAccess;
import org.snaker.engine.access.jdbc.JdbcHelper;

/**
 * 由于snaker-hibernate4不支持hibernate-4.3.11.Final,所以使用自己的实现<br>
 * @author LiZW
 * @version 2016年1月4日 下午2:56:19
 */
public class Hibernate4Access extends HibernateAccess implements DBAccess
{

    @Override
    public Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }

    /**
     * 取得hibernate的connection对象
     */
    @Override
    protected Connection getConnection() throws SQLException
    {
        if (sessionFactory instanceof SessionFactoryImpl)
        {
            SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) sessionFactory;
            ConnectionProvider provider = sessionFactoryImpl.getServiceRegistry().getService(ConnectionProvider.class);
            if (provider != null)
                return provider.getConnection();
        }
        return null;
    }

    public Blob createBlob(byte[] bytes)
    {
        return getSession().getLobHelper().createBlob(bytes);
    }

    @Override
    public void runScript()
    {
        getSession().doWork(new Work()
        {
            public void execute(Connection conn) throws SQLException
            {
                if (JdbcHelper.isExec(conn))
                {
                    return;
                }
                try
                {
                    String databaseType = JdbcHelper.getDatabaseType(conn);
                    String schema = "db/core/schema-" + databaseType + ".sql";
                    ScriptRunner runner = new ScriptRunner(conn, true);
                    runner.runScript(schema);
                }
                catch (Exception e)
                {
                    throw new SnakerException(e);
                }
            }
        });
    }
}
